<?php

class Products extends Controller {
                  
	function Products()
	{
		parent::Controller();	
        if(!admin_session_check()) redirect('admin/login');
        if(!is_allowed("all")) show_404();
        $this->load->model('productsmodel');
        $this->load->library("form_validation");           
	}     
    
    function index()
    {

        $data["list"] = $this->productsmodel->admin_get_all(); 
        $data["response"] = get_response(); 

        $this->load->view('admin/default/head');          
        $this->load->view('admin/default/header', array('selected'=>'products'));  
        $this->load->view("admin/default/nav_products", array('selected' => 'products'));
        $this->load->view("admin/default/quick_search");
        $this->load->view('admin/products/products_list', $data);   
        $this->load->view('admin/default/footer');   

    }     		   
			   
    function edit($id = NULL)
    {
                                                
        if($id == NULL) show_404();

        $this->_process_form(); 

        $data["item"] = $this->productsmodel->admin_get_product($id); 
        if(empty($data["item"])) show_404();

        if($this->input->post("submit_action") !== FALSE){
            $data["images"] = ($this->input->post("more_images")) ? $this->input->post("more_images") : array();
            $data["product_specifications"] = ($this->input->post("specs")) ? $this->input->post("specs") : array();
            $data["product_applications"] = ($this->input->post("apps")) ? $this->input->post("apps") : array();
            $data["product_finishes"] = ($this->input->post("finishes")) ? $this->input->post("finishes") : array();
            $data["supplier"] = $this->input->post("supplier_id") ? $this->input->post("supplier_id") : '';
        } else {
            $data["images"] = $this->productsmodel->get_product_images($id);
            $data["product_specifications"] = $this->productsmodel->admin_get_product_specifications($id);
            $data["product_applications"] = $this->productsmodel->admin_get_product_applications($id);
            $data["product_finishes"] = $this->productsmodel->admin_get_product_finishes($id);
            $data["supplier"] = $data["item"]["id_Supplier"];
        }

        $data["available_specifications"] = $this->productsmodel->admin_get_all_specifications();
        $data["available_units"] = $this->productsmodel->admin_get_all_units();        

        $data["action"] = "update"; 
        $data["token"] = generate_token("products",720);  
        
        $this->load->view('admin/default/head');     
        $this->load->view('admin/default/header', array('selected'=>'products'));     
        $this->load->view("admin/default/nav_products", array('selected' => 'products')); 
        $this->load->view("admin/default/quick_search");
        $this->load->view('admin/products/products_form', $data);   
        $this->load->view('admin/default/footer');   

    }

    function add()
    {

        $this->_process_form();   

        $data["item"] = array(
                "id_Products" => "", 
                "Name_Products" => "", 
                "Introduction_Products" => "",
                "Description_Products" => "",
                "id_Categories" => "",
                "Main_Image" => "",
                "Big_Image" => "",
                "id_Supplier" => "",
                "Code_Products" => "",
                "Price_Products" => "",
                "Currency_Products" => ""
        ); 

        $data["images"] = array();
        $data["product_specifications"] = array();
        $data["product_finishes"] = array();
        $data["product_applications"] = array();
        $data["supplier"] = "";
              
        if($this->input->post("submit_action") !== FALSE){
            if ($this->input->post("more_images")) $data["images"] = $this->input->post("more_images");
            if ($this->input->post("specs")) $data["product_specifications"] = $this->input->post("specs");
            if ($this->input->post("finishes")) $data["product_finishes"] = $this->input->post("finishes");
            if ($this->input->post("apps")) $data["product_applications"] = $this->input->post("apps");
            if ($this->input->post("supplier_id")) $data["supplier"] = $this->input->post("supplier_id");
        }		
		
        $data["available_specifications"] = $this->productsmodel->admin_get_all_specifications();
        $data["available_units"] = $this->productsmodel->admin_get_all_units();        

        $data["action"] = "create";
        $data["token"] = generate_token("products",720);

        $this->load->view('admin/default/head');     
        $this->load->view('admin/default/header', array('selected'=>'products'));  
        $this->load->view("admin/default/nav_products", array('selected' => 'products'));
        $this->load->view("admin/default/quick_search");
        $this->load->view('admin/products/products_form', $data);   
        $this->load->view('admin/default/footer'); 

    }  
	
    function copy($id = NULL)
    {
                                                
        if($id == NULL) show_404();

        $data["item"] = $this->productsmodel->admin_get_product($id); 
        if(empty($data["item"])) show_404();
		     
		$data["images"] = $this->productsmodel->get_product_images($id);
		$data["product_specifications"] = $this->productsmodel->admin_get_product_specifications($id);
		$data["product_applications"] = $this->productsmodel->admin_get_product_applications($id);
		$data["product_finishes"] = $this->productsmodel->admin_get_product_finishes($id);
		$data["supplier"] = $data["item"]["id_Supplier"];
	
		$data["item"]["id_Products"] = "";
		$data["item"]["Name_Products"] .= " [--COPY--]";

        $data["available_specifications"] = $this->productsmodel->admin_get_all_specifications();
        $data["available_units"] = $this->productsmodel->admin_get_all_units();        

        $data["action"] = "create";
        $data["token"] = generate_token("products",720);
        
        $this->load->view('admin/default/head');     
        $this->load->view('admin/default/header', array('selected'=>'products'));     
        $this->load->view("admin/default/nav_products", array('selected' => 'products')); 
        $this->load->view("admin/default/quick_search");
        $this->load->view('admin/products/products_form', $data);   
        $this->load->view('admin/default/footer');   

	}
	
	
	
    function remove($id = false){

        if($id == NULL) show_404();  

        $data["item"] = $this->productsmodel->admin_get_product($id, "id_Products AS id, Name_Products AS title, Introduction_Products AS intro, Description_Products AS description, Main_Image AS image, id_Categories");
        $data["images"] = $this->productsmodel->get_product_images($id);
        $data["product_specifications"] = $this->productsmodel->get_product_specifications($id);
        $data["product_finishes"] = $this->productsmodel->finishes_result_into_string($this->productsmodel->get_product_finishes($id));
        $data["product_applications"] = $this->productsmodel->get_product_applications($id);

        if(empty($data["item"])){

            set_response('error', "The product you're attempting to delete does not exist");
            redirect('admin/products');

        } else {

            $data["controller"] = "admin/products";
            $this->load->model('glossarymodel');

            $this->load->view('admin/default/head');          
            $this->load->view('admin/default/header', array('selected'=>'products'));  
            $this->load->view("admin/default/nav_products", array('selected' => 'products'));
            $this->load->view('admin/products/products_delete', $data);   
            $this->load->view('admin/default/footer');   

        }
    } 
    function confirm_removal($id = false){

        if($id == NULL) show_404();  

        $data["item"] = $this->productsmodel->admin_get_product($id);

        if(empty($data["item"])){

            set_response('error', "The product you're attempting to delete does not exist");
            redirect('admin/products');

        } else {

            $this->productsmodel->admin_delete_product($id);
			$this->_delete_pdf($data["item"]["pdf_Products"]);
            set_response('success', "The product  <i>".$data["item"]["Name_Products"]."</i> was deleted.");
            redirect('admin/products');
        }
    }

    function preview($id = NULL)
    {

        if($this->input->post("submit_action") === FALSE){

            $data["item"] = $this->productsmodel->admin_get_product($id, "id_Products AS id, Name_Products AS title, Introduction_Products AS intro, Description_Products AS description, Main_Image AS image, products.id_Categories AS cat_id, Approved_Products AS approved, Active_Products AS active"); 
            if(empty($data["item"])) show_404();
            $data["images"] = $this->productsmodel->get_product_images($id);
            $data["product_specifications"] = $this->productsmodel->get_product_specifications($id);
            $data["product_finishes"] = $this->productsmodel->finishes_result_into_string($this->productsmodel->get_product_finishes($id));
            $data["product_applications"] = $this->productsmodel->get_product_applications($id);
            $data["action"] = "view"; 

        } else {

           $data["item"] = array(
                        'title' => $this->input->post("name",TRUE),  
                        'intro' => $this->input->post("introduction",TRUE),     
                        'description' => $this->input->post("description",TRUE),
                        'cat_id' => $this->input->post("category",TRUE),
                        'big_image' => $this->input->post("big_image",TRUE), 
                        'image' => $this->input->post("main_image",TRUE));
            
            $data["images"] = ($this->input->post("more_images",TRUE)) ? $this->input->post("more_images",TRUE) : array();
            $input_specs = ($this->input->post("specs",TRUE)) ? $this->input->post("specs",TRUE) : array();

            //clean up $input_specs
            $clean_specs = array();
            foreach ($input_specs as $spec){
                if ($spec["Value"]!=""){
                    $clean_specs[] = array( "Name_Specs" => $this->productsmodel->get_spec_name($spec["id_Specs"]),
                                            "Value" => $spec["Value"],
                                            "name_Units" => $this->productsmodel->get_unit_name($spec["id_Units"]) 
                                            );
                }
            }
            $data["product_specifications"] = $clean_specs;
            $input_finishes = ($this->input->post("finishes",TRUE)) ? $this->input->post("finishes",TRUE) : array();
            $data["product_finishes"] = $this->productsmodel->finishes_result_into_string($this->productsmodel->get_finishes_data($input_finishes));
            $input_apps = ($this->input->post("apps",TRUE)) ? $this->input->post("apps",TRUE) : array();
            $data["product_applications"] = $this->productsmodel->get_applications_data($input_apps);
            $data["action"] = "preview"; 

        }

        $data["cat"] = $this->productsmodel->admin_get_category($data["item"]["cat_id"]);
        //link glossary items     
        $this->load->model('glossarymodel'); 

        $this->load->view('admin/previews/preview_product_template', $data);   

    }
    function deactivate($id = false){
                                   
        if($id == NULL) show_404();                                         
        $data = array('Active_Products' => 0);
        $this->productsmodel->update_product($id, $data);
        $item = $this->productsmodel->admin_get_product($id);
        set_response('success', "The product <i>".$item["Name_Products"].'</i> is now inactive. <a href="'.site_url("admin/products/preview/".$item["id_Products"]).'" rel="view">Click to view</a>');
        redirect('admin/products');
    }
    function activate($id = false){

        if($id == NULL) show_404();  
        $data = array('Active_Products' => 1);
        $this->productsmodel->update_product($id, $data);
        $item = $this->productsmodel->admin_get_product($id);
        set_response('success', "The product <i>".$item["Name_Products"].'</i> is now active. <a href="'.site_url("admin/products/preview/".$item["id_Products"]).'" rel="view">Click to view</a>');
        redirect('admin/products');
    }
    function approve($id = false){

        if(!is_allowed(array(ROLE_ADMIN,ROLE_PUBLISHER))) show_404();
        if($id == NULL) show_404();  

        $data = array('Approved_Products' => 1,
                    'Active_Products' => 1);
        $this->productsmodel->update_product($id, $data);
        $item = $this->productsmodel->admin_get_product($id);
        set_response('success', "The product <i>".$item["Name_Products"].'</i> was approved. <a href="'.site_url("admin/products/preview/".$item["id_Products"]).'" rel="view">Click to view</a>');
        redirect('admin/products');           
    }

    private function _process_form()
    {
                                     
        if($this->input->post("submit_action") !== FALSE){

            if ($this->_validate_form()){  

                if (validate_token("products",$this->input->post("token",TRUE))){  

                    $data = array(
                        'Name_Products' => $this->input->post("name",TRUE),  
                        'Introduction_Products' => $this->input->post("introduction",TRUE),
                        'Description_Products' => $this->input->post("description",TRUE),
                        'id_Categories' => $this->input->post("category",TRUE),
                        'Big_Image' => $this->input->post("big_image",TRUE), 
                        'Main_Image' => $this->input->post("main_image",TRUE),
                        'id_Supplier' => $this->input->post("supplier_id",TRUE),
                        'Code_Products' => $this->input->post("code",TRUE),
                        'Price_Products' => $this->input->post("price",TRUE),
                        'Currency_Products' => $this->input->post("currency",TRUE)
                    );

                    switch($this->input->post("submit_action")){    

                        case 'create':

                          $id = $this->productsmodel->insert_product($data); 
                          set_response('success','Product <i>'.$data['Name_Products'].'</i> was created. <a href="'.site_url("admin/products/preview/".$id).'" rel="view">Click to view</a>');

                        break;
                        case 'update':

                            $id = $this->input->post("id");
                            $this->productsmodel->update_product($id, $data);
                            set_response('success','Product <i>'.$data['Name_Products'].'</i> was updated. <a href="'.site_url("admin/products/preview/".$id).'" rel="view">Click to view</a>');

                        break;        

                    }

                    #### Process images ###
                    // delete previous images
                    $this->productsmodel->admin_delete_product_images($id);
                    //add new images
                    if ($this->input->post("more_images") !== FALSE) {
                        $images = array_filter($this->input->post("more_images", TRUE)); 
                        $this->productsmodel->admin_insert_product_images($id, $images);
						
							// for debuggin, can be deleted:
							//$string = "";
							//for($i=0;$i<count($images);$i++){
							//	$string .= $images[$i]." ** ";
							//}
							//set_response('success', $string.' <a href="'.site_url("admin/products/preview/".$id).'" rel="view">Click to view</a>');
                    } 

                    ### Process specifications ###
                    // delete previous specs
                    $this->productsmodel->admin_delete_product_specifications($id);
                    // add new specs
                    if ($this->input->post("specs") !== FALSE) {
                        $specs = array_filter($this->input->post("specs", TRUE));
                        $this->productsmodel->admin_insert_product_specifications($id, $specs);
                    }   

                    ### Process applications ###
                    // delete previous apps
                    $this->productsmodel->admin_delete_product_applications($id);
                    // add new apps
                    if ($this->input->post("apps") !== FALSE) {                         
                        $apps = array_filter($this->input->post("apps", TRUE)); 
                        $this->productsmodel->admin_insert_product_applications($id, $apps);
                    } 
                      
                    ### Process finishes ###
                    // delete previous finishes
                    $this->productsmodel->admin_delete_product_finishes($id);
                    // add new finishes
                    if ($this->input->post("finishes") !== FALSE) {                         
                        $finishes = array_filter($this->input->post("finishes", TRUE)); 
                        $this->productsmodel->admin_insert_product_finishes($id, $finishes);
                    }
   
   
					$pdf_file = $this->_create_pdf($id);
					$this->productsmodel->update_product($id, array('pdf_Products'=>$pdf_file));
					redirect("admin/products");

                }
            }
        }                         
    }

    private function _create_pdf($product_id = NULL){
			
        //load product data
        $data["item"] = $this->productsmodel->admin_get_product($product_id);        
        
		if (empty($data["item"])) return false;

        $this->load->plugin('to_pdf');

        // page info here, db calls, etc.     
        $data["item"]["applications"] = $this->productsmodel->get_product_applications($product_id); 
        $data["item"]["specifications"] = $this->productsmodel->get_product_specifications($product_id);
        $data["item"]["specifications"][] = array( "Name_Specs" => "Finishes",
                                                   "Value" => $this->productsmodel->finishes_result_into_string($this->productsmodel->get_product_finishes($product_id)) );

        $html = $this->load->view('website/products/product_tearsheet'.INSTANCE_FILE_SUFFIX, $data, true);
		
		$this->_delete_pdf($data["item"]["pdf_Products"]);

        $pdf_file = pdf_create($html, $data["item"]["Name_Products"], FALSE);
		
		return $pdf_file;
		
	}
	
	private function _delete_pdf($filename="") {
		
		if (($filename != "") && (is_file("./".PDF_FOLDER.$filename))) {
			unlink("./".PDF_FOLDER.$filename);
		}
	}
	
    private function _validate_form(){
        
        $config = array(
                        array(
                         'field'   => 'name',
                         'label'   => 'Product name',
                         'rules'   => 'trim|required|xss_clean|max_length[250]'
                        ),
                        array(
                         'field'   => 'introduction',
                         'label'   => 'Introduction',
                         'rules'   => 'trim|xss_clean'
                        ),
                        array(
                         'field'   => 'description',
                         'label'   => 'Description',
                         'rules'   => 'trim|xss_clean'
                        ),
                        array(
                         'field'   => 'category',
                         'label'   => 'Category',
                         'rules'   => 'trim|required|xss_clean'
                        ),             
                        array(
                         'field'   => 'big_image',
                         'label'   => 'Top Gallery Image',
                         'rules'   => 'trim|xss_clean'
                        ),
                        array(
                         'field'   => 'main_image',
                         'label'   => 'Main Image',
                         'rules'   => 'trim|xss_clean'
                        ),
                        array(
                         'field'   => 'supplier_id',
                         'label'   => 'Supplier',
                         'rules'   => 'xss_clean'
                        ),
                        array(
                         'field'   => 'code',
                         'label'   => 'Product Code',
                         'rules'   => 'trim|xss_clean|max_length[36]'
                        ),
                        array(
                         'field'   => 'price',
                         'label'   => 'Price',
                         'rules'   => 'trim|xss_clean|numeric|max_length[36]'
                        ),
                        array(
                         'field'   => 'currency',
                         'label'   => 'Currency',
                         'rules'   => 'xss_clean'
                        )
                    );
        
                                                 
        $this->form_validation->set_rules($config);       
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        
        if ($this->form_validation->run($this) == FALSE){
            return FALSE;
        }else
            return TRUE;

    }


    public function get_application_list()
    {
        $all = $this->productsmodel->admin_get_all_applications();
        $r = '';
        foreach($all as $row){
            $class = ($row['Active_Applications']==1)?"active":"inactive";
            $r .= '<label class="list_block search '.$class.'" style="width:245px; float:left; clear:none">';
            $r .= '<input name="apps[]" type="checkbox" value="'.$row['id_Applications'].'" style="display:none" />';
            $r .= '<span class="title" style="display:inline; width:auto;">'.$row['Name_Applications'].'</span>';
            $r .= '</label>';
        }                     
        echo $r;
    }    

    public function get_finishes_list()
    {
        $all = $this->productsmodel->admin_get_all_finishes();
        $r = '';
        foreach($all as $row){
            $class = ($row['Active_Finishes']==1)?"active":"inactive";        
            $r .= '<label class="list_block search '.$class.'" style="width:245px; float:left; clear:none">';
            $r .= '<input name="finishes[]" type="checkbox" value="'.$row['id_Finishes'].'" style="display:none" />';
            $r .= '<span class="title" style="display:inline; width:auto;">'.$row['Name_Finishes'].'</span>';
            $r .= '</label>';
        }
        echo $r;
    }                                
    public function get_suppliers_list()
    {
        $all = $this->productsmodel->admin_get_all_suppliers('id_Supplier AS id, Code_Supplier AS code, Name_Supplier As name');         
        echo json_encode($all);                 
    }           
    public function get_supplier_info()
    {
        $id = $this->input->post('id', TRUE);
        $data = $this->productsmodel->admin_get_supplier_info($id);  
        $data['Address_Supplier'] = nl2br($data['Address_Supplier']);
        $data['Address2_Supplier'] = nl2br($data['Address2_Supplier']);
        echo json_encode($data);                 
    }       

    public function export(){                                                         
        $this->load->plugin('to_excel');

        $this->db->select('*');
        $this->db->from('products');
        // run joins, order by, where, or anything else here
        $query = $this->db->get();
        to_excel($query, 'products'.INSTANCE_FILE_SUFFIX);
    }    


	/**
	* Returns the pdf file for download. Creates it if doesn't exist.
	*/
    public function pdf($id = FALSE)
    {
        if ($id===FALSE) show_404();
        //load product data
        $product = $this->productsmodel->admin_get_product($id);        
        if (empty($product)) show_404();
		
		//if pdf doesn't exist, create it now
		if (empty($product["pdf_Products"])) {
			$pdf_file = $this->_create_pdf($id);
			$this->productsmodel->update_product($id, array('pdf_Products'=>$pdf_file));
			$product["pdf_Products"] = $pdf_file;
		}
		
		$this->load->helper('download');
		$data = file_get_contents("./".PDF_FOLDER.$product["pdf_Products"]);
		force_download($product["pdf_Products"], $data);
    }     
}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */
